// websocket.service.ts

import { WebSocketStatus } from '@/enums/commonEnum';

export class WebSocketService {
  private socket?: WebSocket;
  private messageListeners: ((data: any) => void)[] = [];
  private status: WebSocketStatus = WebSocketStatus.CLOSED;

  // 提供一个只读属性来获取连接状态
  get readyState(): number {
    return this.status;
  }
  constructor(private url: string) {}

  // 连接到WebSocket服务器
  connect() {
    if (this.socket && (this.socket.readyState === WebSocket.OPEN || this.socket.readyState === WebSocket.CONNECTING)) {
      console.warn('WebSocket is already connected or connecting.');
      return;
    }

    this.socket = new WebSocket(this.url);

    this.socket.onopen = () => {
      this.status = WebSocketStatus.CONNECTING;
    };
    this.socket.onmessage = (event) => {
      try {
        this.status = WebSocketStatus.OPEN;
        const data = event.data;
        this.messageListeners.forEach((listener) => listener(data));
      } catch (error) {
        console.error('Error parsing WebSocket message:', error);
      }
    };

    this.socket.onerror = (error) => {
      this.status = WebSocketStatus.CLOSING;
      console.error('WebSocket Error:', error);
      // 这里可以添加错误处理逻辑，比如尝试重新连接
    };

    this.socket.onclose = () => {
      console.log('WebSocket Connection Closed');
      this.status = WebSocketStatus.CLOSED;
      // 这里可以添加重新连接的逻辑
    };
  }

  // 发送消息到WebSocket服务器
  send(message: any) {
    if (this.socket && this.socket.readyState === WebSocket.OPEN) {
      this.socket.send(JSON.stringify(message));
    } else {
      console.error('WebSocket is not connected.');
    }
  }

  // 添加消息监听器
  onMessage(listener: (data: any) => void) {
    this.messageListeners.push(listener);
  }

  // 添加链接错误的消息监听器
  onError(listener: (error: any) => void) {
    this.socket?.addEventListener('error', listener);
  }

  // 添加关闭连接的消息监听器
  onclose(listener: (error: any) => void) {
    this.socket?.addEventListener('close', listener);
  }

  // 移除消息监听器
  offMessage(listener: (data: any) => void) {
    this.messageListeners = this.messageListeners.filter((cb) => cb !== listener);
  }

  // 关闭WebSocket连接
  disconnect() {
    if (this.socket) {
      this.socket.close();
      this.socket = undefined;
    }
  }
}

// 使用示例（在Vue组件中）
// import { WebSocketService } from './websocket.service';
//
// const wsService = new WebSocketService('wss://example.com/websocket');
// wsService.connect();
// wsService.onMessage(data => {
//   console.log('Received data:', data);
// });
//
// // 发送消息
// wsService.send({ type: 'ping', message: 'Hello, WebSocket!' });
